<script setup lang="ts">
import type { ImageProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import {
  getcommentservice,
  getdowncommentservice,
  getmenuitemListByrecommendByitemIdservice,
  getuserdetailservice,
  insertcommentservice
} from "../api/food.js"
import {ref, onMounted, computed, reactive, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
const fistcomment=reactive({
  username: '',
  commentTime: '',
  rating: 0,
  comment:''

});
const routes = useRoute();
const pageSize = 4;
const currentPage = ref(1); // 当前页数
const activeNames = ref(['1'])
const comments = reactive([]);
const commenttext=ref('');
const rating=ref(0);
const routers=useRouter();

const itemList=reactive([])
const fits = [
  'fill',
  'contain',
  'cover',
  'none',
  'scale-down',
] as ImageProps['fit'][];
const item = ref({
  itemid: 0,
  itemname: '',
  imageUrl: '',
  price: '',
  description: '',
});

const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return comments.slice(startIndex, endIndex);
});

const totalItems = computed(() => comments.length);

const cardRows = computed(() => {
  const rows = [];
  for (let i = 0; i < currentPageItems.value.length; i += 4) {
    rows.push(currentPageItems.value.slice(i, i + 4));
  }
  return rows;
});

const getitem = () => {
  item.value.imageUrl = routes.query.imageUrl as string;
  item.value.itemname = routes.query.itemname as string;
  item.value.price = routes.query.price as string;
  item.value.description = routes.query.description as string;
  item.value.itemid = Number(routes.query.id);
};
watch(() => routes.query, async (newQuery, oldQuery) =>{
  if (newQuery !== oldQuery){
    await getitem();
    await  getcomment(item).then(() => {
      getuserdetail(comments);
    });
    await  getitemListByrecommendByitem(item)
  }},{
    immediate: true
  , deep: true
})
onMounted(() => {
  getitem();
  getitemListByrecommendByitem(item)
  getcomment(item).then(() => {
    getuserdetail(comments).then(()=>{
      fistcomment.username=comments[0].user.username
      fistcomment.commentTime=comments[0].commentTime
      fistcomment.commentTime=formatDateTime(fistcomment.commentTime)
      fistcomment.rating=comments[0].rating
      fistcomment.comment=comments[0].comment
      comments.splice(0, 1); // 移除第一个元素
    });

  });

});
const itemdetail = async(foodItem)=> {
  await routers.push({
    path:'/orderfood/itemdetail',
    query: {
      id:foodItem.id,
      itemname: foodItem.itemname,
      imageUrl:foodItem.imageUrl,
      price:foodItem.price,
      description:foodItem.description
    }
  })

}

const getcomment = async (item) => {
  if (item.id !== null) {
    const response = await getcommentservice(item.value.itemid);
    if (response.code === 200) {
      comments.splice(0, comments.length);
      response.date.forEach(comment => {
        // 添加一个属性来存储该一级评论关联的二级评论
        comment.commentTime=formatDateTime(comment.commentTime)
        comments.push({ ...comment, downcomments: [], showDownComments: false ,user: {},showinsertcomment: false});
      });

      return Promise.resolve(); // 确保在评论数据填充完成后返回 Promise
    }
  }
};


const getdowncomment = async (comment, item) => {
  comment.downcomments.splice(0, comment.downcomments.length);
  const response = await getdowncommentservice(comment.id, item.itemid);
  if (response.code === 200) {
    response.date.forEach(downcomment => {
      comment.downcomments.push(downcomment);
    });
    // 更新此一级评论的二级评论的可见性状态
    comment.showDownComments = true;
  }
};

const hideDownComments =(comment) => {
  console.log(comment);
  console.log(comment.showDownComments)
  comment.showDownComments = false;
}
const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};
const getuserdetail = async (comments) => {
  for (const comment of comments) {
    const response= await getuserdetailservice(comment.userId)
    if(response.code === 200){
      comment.user = response.date;
    }
else {
  console.log("添加用户信息执行失败")
    }
  }

}

const showcomment = (comment) => {
  comment.showinsertcomment=!comment.showinsertcomment
}

const insercomment = async (commenttext,rating,comment)=>{
const response = await insertcommentservice(commenttext,rating,comment.id,comment.itemId)
if(response.code === 200){
  ElMessage({
    message: '评论成功',
    type: 'success',
  })
  comment.showinsertcomment=false;
  console.log("评论执行成功")


}else {
  ElMessage({
    message: '评论失败请重试',
    type: 'warning',
  })
  console.log("评论执行失败")
}

}
const getitemListByrecommendByitem =async (item) => {
  const response = await getmenuitemListByrecommendByitemIdservice(item.value.itemid)
  if(response.code === 200){
    itemList.splice(0,itemList.length)
    response.date.forEach(item => {
      itemList.push(item)
    })
  }
  console.log(response)
}
</script>

<template>
  <div class="common-layout">
    <el-container class="containner">
      <el-header class="containner-header">
        <el-card style="max-width: 600px">
          <template #header>
            <div class="card-itename">{{ item.itemname }}</div>
          </template>
          <img :src="item.imageUrl" style="width: 100%" />
          <p class="card-price">¥: {{ item.price }}</p>
          <div class="demo-collapse">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="详情" name="1">
                <p class="collapse-p">大厨描述:{{ item.description }} </p>
              </el-collapse-item>
              <el-collapse-item title="评论" name="2">
                <div class="top-comment">
                  <el-tag type="primary">被置顶</el-tag>
                  <p><strong>评论者：</strong>{{ fistcomment.username }}</p>
                  <p><strong>评论时间：</strong>{{ fistcomment.commentTime }}</p>
                  <p><strong>评论内容：</strong>{{ fistcomment.comment }}</p>
                  <p><strong>评分：</strong>
                    <el-rate
                        v-model="fistcomment.rating"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value} points"
                    /></p>
                </div>
                <div v-for="(row, index) in cardRows" :key="index" class="card-row">
                <div v-for="comment in row" :key="comment.id" class="comment">
                  <p><strong>评论者：</strong>{{ comment.user.username }}</p>
                  <p><strong>评论时间：</strong>{{ comment.commentTime }}</p>
                  <p><strong>评论内容：</strong>{{ comment.comment }}</p>
                  <p><strong>评分：</strong>
                    <el-rate
                        v-model="comment.rating"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value} points"
                    /></p>

                  <div v-if="comment.showDownComments">
               ---------------------------------------------------------------------
                    <div v-for="secondComment in  comment.downcomments" :key="secondComment.id" class="comment">
                      <p><strong>回复者：</strong>匿名会员{{secondComment.id}}</p>
                      <p><strong>评论时间：</strong>{{ secondComment.commentTime }}</p>
                      <p><strong>评论内容：</strong>{{ secondComment.comment }}</p>
                      <p><strong>评分：</strong>
                        <el-rate
                            v-model="secondComment.rating"
                            disabled
                            show-score
                            text-color="#ff9900"
                            score-template="{value} points"
                        /></p>
                      <el-button type="info" @click="hideDownComments(comment)">收起</el-button>
                      <el-divider border-style="dashed" />
                    </div>
                  </div>
                  <div>
                    <el-button type="info" class="button_comment" @click="getdowncomment(comment, item)">查看更多</el-button>
                    <el-button type="success"  @click="showcomment(comment)">回复</el-button>
                  </div>
                  <div v-show="comment.showinsertcomment">
                    <p><strong>回复内容：</strong>
                      <el-input
                          v-model="commenttext"
                          maxlength="30"
                          style="width: 240px"
                          placeholder="Please input"
                          show-word-limit
                          type="textarea"
                      /></p>
                    <p><strong>评分：</strong>
                      <el-rate v-model="rating" allow-half /></p>
                    <el-button type="success"  @click="insercomment(commenttext,rating,comment)">确认回复</el-button>
                  </div>

                  <el-divider border-style="dashed" />
                </div>
                </div>
                <el-pagination
                    small
                    background
                    layout="prev, pager, next"
                    :total="totalItems"
                    :page-size="pageSize"
                    v-model:currentPage="currentPage"
                    class="mt-4"
                />
              </el-collapse-item>
              <el-collapse-item title="猜你喜欢" name="3">

                <div class="w like">
                  <div class="like-hd">
                    <h3>猜你喜欢</h3>
                    <a href="#">换一批</a>
                  </div>
                  <div class="like-bd">
                    <ul v-for="(item, index) in itemList  " :key="index"  >
                      <li>
                        <img :src="item.imageUrl" alt="">
                        <h5><a href="#" @click="itemdetail(item)">{{item.description}}</a>
                          <i>&yen;{{item.price}}</i>
                        </h5>

                      </li>
                    </ul>
                  </div>
                </div>


              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </el-header>
      <el-main></el-main>
      <el-footer></el-footer>
    </el-container>
  </div>
</template>

<style scoped>
.top-comment {
  /* 在这里添加你想应用到置顶评论的样式 */
  background-color: #f5f5f5; /* 示例：改变背景色 */
  font-weight: bold; /* 示例：加粗字体 */
  padding-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-left: 10px;
  margin-right: 10px;
  border: 1px solid black;
  margin-top: 10px;
  margin-bottom: 10px;
}
.containner { }
.containner-header {
  height: 400px;
  margin-top: 50px;
}
.card-price { color: red; }
.card-itename {
  font-family: 隶书;
  color: red;
  font-size: 100px;
}
.collapse-p {
  font-family: 隶书;
  color: darkgoldenrod;
  font-size: 20px;
}
.button_comment { margin-right: 20px; }
/* 猜你喜欢模块 */
.like {
  height: 261px;
  margin-top: 30px;
}

.like-hd {
  height: 30px;
  border-bottom: 1px solid #ebebeb;
}

.like-hd h3 {
  float: left;
  font-size: 18px;
  font-weight: normal;
}

.like-hd a {
  float: right;
  margin-right: 20px;
}

.like-hd a::after {
  font-family: 'iconfont';
  content: '\e6e1';
  margin-left: 7px;
}

.like-bd {
  height: 231px;
  border: 1px solid #ebebeb;
  border-top: 0;
  overflow: hidden;
}

.like-bd ul {
  width: 1210px;
}

.like-bd li {
  float: left;
  width: 200px;
}

.like-bd img {
  width: 200px;
  height: 120px;
}

.like-bd h5 {
  height: 65px;
  position: relative;
  margin-left: 35px;
  font-weight: normal;
}

.like-bd h5 a {
  /* 溢出隐藏 */
  overflow: hidden;
  /* 文字溢出省略号显示 */
  text-overflow: ellipsis;
  /* 弹性伸缩盒子模型显示 */
  display: -webkit-box;
  /* 限制显示行数 */
  -webkit-line-clamp: 2;
  /* 设置或检索伸缩盒对象的子元素的排列方式 */
  -webkit-box-orient: vertical;
}

.like-bd h5:nth-child(-n+5):after {
  content: '';
  position: absolute;
  right: 0;
  bottom: 9px;
  height: 62px;
  width: 1px;
  background-color: #ededed;
}

.like-bd i {
  font-size: 18px;
  color: #df3033;
}
</style>
